package com.gzq.singleton.practice0;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class DCLSingleton implements Serializable {

	/**
	 * 20fenzhong
	 */
	private static final long serialVersionUID = 1L;

	public static void main(String[] args)
			throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException,
			IllegalArgumentException, InvocationTargetException, IOException, ClassNotFoundException {
		DCLSingleton singleton1 = DCLSingleton.getSingleton();
		DCLSingleton singleton2 = DCLSingleton.getSingleton();
		System.out.println(singleton1);
		System.out.println(singleton2);

		// 反射
		Constructor<DCLSingleton> constructor = DCLSingleton.class.getDeclaredConstructor();
		constructor.setAccessible(true);
		DCLSingleton newInstance = constructor.newInstance();
		System.out.println(newInstance);

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream(baos);
		oos.writeObject(singleton1);

		byte[] byteArray = baos.toByteArray();

		InputStream inputStream = new ByteArrayInputStream(byteArray);
		ObjectInputStream ois = new ObjectInputStream(inputStream);
		Object readObject = ois.readObject();
		System.out.println(readObject);

	}

	private static DCLSingleton singleton;

	private DCLSingleton() {

	}

	public static DCLSingleton getSingleton() {
		if (singleton == null) {
			synchronized (DCLSingleton.class) {
				/**
				 * 如果new之后还有很多步骤，那么其他进来的获取单例对象的客户端。 可能会获取到一个初始化不完成的类。
				 */
				if (singleton == null) {
					singleton = new DCLSingleton();
					// 后续还有很多步骤
				}
			}
		}
		return singleton;
	}
}
